
/**
 * getToken  获取token
 * 
 */

/**
 * Created by  lizhihang
 */

'use strict';
var express = require('express');
var router = express.Router();
var mongo = require('mongoskin');
var jwt = require('jsonwebtoken');

var db = mongo.db("mongodb://localhost:27017/weGDUT");
db.bind('weGDUT');




function suggestion(req, res, next) {
  var token = req.body.token
  console.log(req.body.token)
  var suggestion = req.body.suggestion
  console.log(req.body.suggestion)

  if (suggestion) {
    //尝试是否可以解析token，如果是格式正确的token，允许查找数据库，并且继续搜索教务系统
    try {
      let decoded = jwt.verify(token, 'thefirstminappofvtmer');
      console.log(decoded)
      var username = decoded.username;
      // var openid = decoded.openid;
      //查找数据库中是否已经绑定
      // var result = new Promise((resolve, reject) => {
      //   db.weGDUT.find({ openid: openid }).toArray(function (err, items) {
      //     resolve(items)
      //   })
      // })
      // var users
      // result.then(function (value) {
        // users = value[0]
        // console.log('openid:'+users.openid)
        
				var db = mongo.db("mongodb://localhost:27017/suggestion");
        db.bind('suggestion');       
        if (username !='' ) {
          db.suggestion.insert({
            nickName:username,
						// openid:users.openid,
            suggestion:suggestion,
				    time: new Date(),
          })
          res.send({ code: 200, message: 'success' })
        } else {
          res.send({ code: 500, message: 'token invid' })
        }
      // })
    } catch (err) {
      res.send({ code: 401, message: 'token invid' + err })
    }
  } else {
    res.send({ code: 404, message: 'suggestion is required' })
  }
}



module.exports = suggestion;
